package com.jzr.task.config.mutildb;

import com.jzr.common.util.ArrayUtil;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@EnableTransactionManagement
@Configuration
@MapperScan(basePackages = {"com.jzr.task.db2.mapper"},sqlSessionFactoryRef = "db2SqlSessionFactory")
public class Db2Config {
//    @Bean(name = "db2PaginationInterceptor")
//    public PaginationInterceptor db2PaginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        //paginationInterceptor.setLocalPage(true);
//        return paginationInterceptor;
//    }

    @Bean(name = "db2")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.hikari.db2")
    public DataSource db2() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
        //return new HikariDataSource();
        //return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = "db2SqlSessionFactory")
    @Primary
    public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2") DataSource db2 ) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(db2);
        sessionFactory.setTypeAliasesPackage("com.cenxi.scm.model.db2");

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sessionFactory.setConfiguration(configuration);

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources1 =resolver.getResources("classpath*:mapper/db2/*.xml");
        sessionFactory.setMapperLocations(ArrayUtil.mergeArrays(resources1));
        return sessionFactory.getObject();
    }


}